package com.livideo.baseutilslibrary.utils;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;


import java.io.File;

/**
 *
 * @Author： xuchangqing
 * @Time： 2021/6/29 1:29 PM
 * @description：  保存视频
 */

public class DownloadTool {

    private Context mContext;
    private String path;//文件保存路径
    private BroadcastReceiver broadcastReceiver;

    public DownloadTool(Context mContext, String path) {
        this.mContext = mContext;
        this.path = path;
    }

    /**
     *保存视频到相册
     */
    public void downloadVideo(){
        DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(path);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        //设置允许使用的网络类型，这里是移动网络和wifi都可以
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //禁止发出通知，既后台下载，如果要使用这一句必须声明一个权限：android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
        //request.setShowRunningNotification(false);
        //不显示下载界面
        request.setVisibleInDownloadsUi(false);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//        final String foldName = Config.getDirOffLineVideo();
        long timeStamp = System.currentTimeMillis();
        String foldName = Environment.getExternalStorageDirectory() + File.separator + "DCIM"
                + File.separator + "Camera" + File.separator;
        File file = new File(foldName, timeStamp + ".mp4");
        request.setDestinationUri( Uri.fromFile(file));
        long id = downloadManager.enqueue(request);
        registerListener(mContext,id);
        Toast.makeText(mContext, "视频开始下载", Toast.LENGTH_SHORT).show();
    }


    //DownLoadManager 的监听回调
    public void registerListener(Context context, final long id) {
        // 注册广播监听系统的下载完成事件。
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (ID == id) {
                    Toast.makeText(context,"视频已保存到本地",Toast.LENGTH_SHORT).show();
                }
            }
        };
        context.registerReceiver(broadcastReceiver, intentFilter);
    }

}
